﻿/// <reference path="/scripts/jQuery/jquery-1.4.1-vsdoc.js"/>
/// <reference path="/scripts/jQuery/jquery-ui-vsdoc_1.js"/>
/// <reference path="/scripts/Common/Globals.js"/>


var roles = null;
var userRoles = null;
var usersWithRoles = null;

function Load_Users() {
    var inp = "<div class='ui-widget'>";
    inp += "<label for='txtUsers'>User Id: </label>";
    inp += "<input id='txtUsers' type='text' />";
    inp += "</div>";
    inp += "<div id='UsersTable'/>";
    inp += "<div id='UserRolesTable'/>";
        
    $("#Users").html(inp);

    CallWebService(adminRolesGetUrl, null,
                function (result) {
                    var response = JSON.parse(result.d);
                    if (response.IsSuccess == false) {
                        ShowErrorMessage(response);
                    } else {
                        roles = response.Payload;                       
                    }
                });

    $("#txtUsers").keyup(function (e) {
        if (e.keyCode == 13) {
            Load_Users_ByName();
        }
    });

    $("#txtUsers").autocomplete({
        source: function (request, response) {
            CallWebService(adminUserGetUsers, { "partialUsername": $("#txtUsers").val() },
                    function (result) {
                        var resp = JSON.parse(result.d);
                        if (resp.IsSuccess == false) {
                            ShowErrorMessage(resp);
                        } else {
                            response($.map(resp.Payload,
                                        function (item) {
                                            return { label: item.Firstname + ' ' + item.Lastname, value: item.UserName }
                                        }
                            ));
                        }
                    });
        },
        change: function (event, ui) {
            //Load_Users_ByName();
        },
        minLength: 1,
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        },
        delay: 1000
    });
}

function Load_Users_ByName() {
    var inp = { "partialUserName": $("#txtUsers").val() };
    CallWebService(adminUserGetUsersWithRoles, inp,
                function (result) {
                    var response = JSON.parse(result.d);
                    if (response.IsSuccess == false) {
                        ShowErrorMessage(response);
                    } else {
                        usersWithRoles = response.Payload;
                        var tbl = "<table id='usersDataTable' class='Striped'>";
                        tbl += "<thead><tr><th style='width:60px'/><th>User</th><th>First Name</th><th>Last Name</th><th>Roles</th></tr></thead>";
                        tbl += "<tbody>";
                        $.each(usersWithRoles, function (index) {
                            tbl += "<tr>";
                            var tempRolesString = "";
                            $.each(this.Roles, function (index) {
                                tempRolesString += this.RoleId + "|";
                            });

                            tbl += "<td><input id='btnUserEdit_" + index + "' class='EditUser' type='button'" + "' userName='" + this.UserName + "'" +
                            " userId='" + this.UserId + "'" +
                            " value='Edit' index='" + index + "' Roles='" + tempRolesString + "'/>&nbsp";
                            /* tbl += "<input id='btnUserDelete_" + index + "' class='DeleteUser' type='button' index='" + index + "' value='Delete'/>&nbsp"; */
                            tbl += "<input id='btnUserSave_" + index + "' class='SaveUser' type='button' index='" + index + "' value='Save'  style='display:none'/></td>";
                            tbl += "<td>" + "<span id= 'rd_User_Name_" + index + "' userId='" + this.UserId + "'>" + this.UserName + "</span>" +
                            "<input id='ed_User_Name_" + index + "' type='text' value='" + this.UserId + "' style='display:none;width:100%'/>" +
                            "</td>";
                            //firstname
                            tbl += "<td>" + "<span id= 'rd_User_Firstname_" + index + "' userId='" + this.UserId + "'>" + this.Firstname
                            + "</span>" +
                            "<input id='ed_User_Firstname_" + index + "' type='text' value='" + this.Firstname + "' style='display:none;width:100%'/>" +
                            "</td>";
                            //lastname
                            tbl += "<td>" + "<span id= 'rd_User_Lastname_" + index + "' userId='" + this.UserId + "'>" + this.Lastname
                            + "</span>" +
                            "<input id='ed_User_Lastname_" + index + "' type='text' value='" + this.Lastname + "' style='display:none;width:100%'/>" +
                            "</td>";
                            // roles
                            tbl += "<td>" + "<span id= 'rd_User_Roles_" + index + "' userId='" + this.UserId;
                            $.each(this.Roles, function (index) {
                                tbl += this.RoleName + "<br/>";
                            });
                            tbl += "</span>" + "<input id='ed_User_Roles_" + index + "' type='text' value='";
                            tbl += "' style='display:none;width:100%'/>";
                            "</td>";
                            tbl += "</tr>";
                        });
                        tbl += "</tbody>";
                        tbl += "</table>";
                        /* tbl += "<input id='NewUser' type='button' value='New'/>"; */
                        $("#UsersTable").html(tbl);

                        // Add striping
                        $("#usersDataTable tr:nth-child(even)").addClass("alt");
                        $("#usersDataTable tr:nth-child(odd)").addClass("alt2");
                        $("#usersDataTable tr:gt(0)").mouseenter(function () { $(this).addClass("over"); }).mouseleave(function () { $(this).removeClass("over"); });
                        // Delete User
                        /*
                        $(".DeleteUser").button().click(function () {
                        if (confirm("Do you want to delete?") == true) {
                        /*
                        var input = { "roleId": $(('#rd_Role_Name_' + $(this).attr('index'))).attr("RoleId") };
                        CallWebService(adminRolesDeleteUrl, input, function (result) {
                        var response = JSON.parse(result.d);
                        if (response.IsSuccess == false) {
                        ShowErrorMessage(response);
                        }
                        Load_Roles();
                        });
                        */
                        /*    }
                        });
                        */
                        // Edit Role Button
                        $(".EditUser").button().click(function () {
                            var userId = $(this).attr("userId");
                            var uiUsersRole = "<div>";
                            uiUsersRole += "<table id='tblRoles'>";
                            uiUsersRole += "<tr>";
                            uiUsersRole += "<th>";
                            uiUsersRole += "<span>Role</span>";
                            uiUsersRole += "</th><th/>";
                            uiUsersRole += "</tr>";

                            var userWithRole = null;
                            var userName = $(this).attr("UserName");
                            $.each(usersWithRoles, function (index) {
                                if (this.UserName == userName) {
                                    userWithRole = this;
                                }
                            });
                            $.each(roles, function (index) {

                                uiUsersRole += "<tr>";
                                uiUsersRole += "<td>";
                                uiUsersRole += "<input type='checkbox' class='roleSelection'";
                                uiUsersRole += " roleId='" + this.RoleId + "'";
                                var tempRoleId = this.RoleId;
                                $.each(userWithRole.Roles, function (index) {
                                    if (this.RoleId == tempRoleId) {
                                        uiUsersRole += " checked='checked'"
                                    }
                                });
                                uiUsersRole += "/>";
                                uiUsersRole += "</td>";
                                uiUsersRole += "<td>";
                                uiUsersRole += "<span>" + this.RoleName + "</span>";
                                uiUsersRole += "</td>";
                                uiUsersRole += "</tr>";

                            });
                            uiUsersRole += "</table>";
                            uiUsersRole += "</div>";

                            $('#UserRolesTable').html(uiUsersRole).dialog({
                                autoOpen: true,
                                closeOnEscape: true,
                                draggable: false,
                                height: '400',
                                width: '500',
                                title: "<span style='font-size:16px'>" + "Selected Roles for User: " + $(this).attr('userName') + "</span>",
                                modal: true,
                                resizable: false,
                                buttons: {
                                    "Close": function () {
                                        $(this).dialog("close");
                                    },
                                    "Save": function () {
                                        // Loop all roles and remove user from role
                                        $("#tblRoles .roleSelection").each(function (index) {
                                            //alert($(this).attr('roleId') + $(this).attr('checked'));
                                            CallWebService(adminUserDeleteUserFromRole, { "userId": userId, "roleId": $(this).attr('roleId') },
                                            function (response) {
                                                response = JSON.parse(response.d);
                                                if (response.IsSuccess == false) {
                                                    ShowErrorMessage(response);
                                                }
                                            });
                                        });

                                        // Loop selected roles and add user to role
                                        //adminUserAddUserToRole
                                    }
                                }
                            });
                            /*
                            switch ($(this).val()) {
                            case "Edit":
                            $(this).val("Cancel");
                            $(("#ed_User_Name_" + $(this).attr('index'))).show();
                            $(("#ed_Role_Desc_" + $(this).attr('index'))).show();
                            $(("#rd_Role_Name_" + $(this).attr('index'))).hide();
                            $(("#rd_Role_Desc_" + $(this).attr('index'))).hide();
                            $(("#btnRoleDelete_" + $(this).attr('index'))).hide();
                            $(("#btnUserSave_" + $(this).attr('index'))).show();
                            break;
                            default:
                            $(this).val("Edit");
                            $(("#ed_User_Name_" + $(this).attr('index'))).hide();
                            $(("#ed_Role_Desc_" + $(this).attr('index'))).hide();
                            $(("#rd_Role_Name_" + $(this).attr('index'))).show();
                            $(("#rd_Role_Desc_" + $(this).attr('index'))).show();
                            $(("#btnRoleDelete_" + $(this).attr('index'))).show();
                            $(("#btnUserSave_" + $(this).attr('index'))).hide();
                            break;
                            }
                            */
                        });
                        // Update Role
                        $(".SaveUser").button().click(function () {
                            var inp = { "roleId": $(('#rd_Role_Name_' + $(this).attr('index'))).attr("RoleId"),
                                "roleName": $(("#ed_User_Name_" + $(this).attr('index'))).val(), "description": $(("#ed_Role_Desc_" + $(this).attr('index'))).val()
                            };
                            CallWebService(adminRolesSaveUrl, inp, function (result) {
                                if (JSON.parse(result.d).IsSuccess == false) {
                                    alert("Save Failed.");
                                }
                            });
                            $(this).hide();
                            $(("#btnRoleDelete_" + $(this).attr('index'))).show();
                            $(("#btnRoleEdit_" + $(this).attr('index'))).show().val("Edit"); ;
                            $(("#rd_Role_Name_" + $(this).attr('index'))).show();
                            $(("#rd_Role_Desc_" + $(this).attr('index'))).show();
                            $(("#ed_User_Name_" + $(this).attr('index'))).hide();
                            $(("#ed_Role_Desc_" + $(this).attr('index'))).hide();
                            Load_Roles();
                        });
                        // Add Role
                        /*
                        $("#NewRole").button().click(function () {
                        $("#NewRole").attr("disabled", true);
                        $("#rolesDataTable > tbody:last").append("<tr id='RoleAddRow'><td><input id='btnAddRole' type='button' value='Add'/>" +
                        "<input id='btnCancelAddRole' type='button' value='Cancel'/></td><td><input id='ed_Role_Name' style='width:100%' type='text'/></td>" +
                        "<td><input type='text' id='ed_Role_Desc' style='width:100%'/></td></tr>");
                        $("#btnCancelAddRole").button().click(function () { $('#RoleAddRow').remove(); $("#NewRole").attr("disabled", false); });
                        $("#btnAddRole").button().click(function () {
                        $("#NewRole").attr("disabled", false);
                        var inp = { "roleId": "", "roleName": $("#ed_Role_Name").val(), "description": $("#ed_Role_Desc").val() };
                        CallWebService(adminRolesSaveUrl, inp, function (result) {
                        var response = JSON.parse(result.d);
                        if (response.IsSuccess == false) {
                        ShowErrorMessage(response);
                        }
                        Load_Roles();
                        });
                        $('#RoleAddRow').remove();
                        });
                        });
                        */
                    }
                });
}